package com.lzs.system.security;


import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.lzs.common.config.Constant;
import com.lzs.common.dao.SysMenuDao;
import com.lzs.common.dao.UserAuthDao;
import com.lzs.common.pojo.common.SysUser;
import com.lzs.common.redis.RedisUserInfo;
import com.lzs.common.service.UserAuthService;
import com.lzs.common.utils.SecurityUser;
import com.lzs.common.vo.GetUserPowerVo;
import com.lzs.common.dao.SysRoleDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component("userDetailsService")
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    private UserAuthDao userAuthDao;
    @Autowired
    private SysRoleDao sysRoleDao;
    @Autowired
    private SysMenuDao sysMenuDao;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserAuthService userAuthService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 1. 查询用户
        SysUser sysUser = userAuthDao.selectOne(Wrappers.<SysUser>lambdaQuery()
                .select()
                .eq(SysUser::getUsername, username));
        if (sysUser == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        RedisUserInfo redisUserInfo = new RedisUserInfo();
        redisUserInfo.setId(sysUser.getId());
        redisUserInfo.setUsername(sysUser.getUsername());
        GetUserPowerVo userPower = userAuthService.getUserPower(sysUser.getId());
        List<String> roleNameList = userPower.getRoleNameList();
        List<String> menuCodeList = userPower.getMenuCodeList();
        //用户角色权限
        List simpleGrantedAuthorityList = new ArrayList<SimpleGrantedAuthority>();
        for (String roleName : roleNameList) {
            simpleGrantedAuthorityList.add(new SimpleGrantedAuthority(Constant.ROLE_+roleName));
        }
        for (String menuCode : menuCodeList) {
            simpleGrantedAuthorityList.add(new SimpleGrantedAuthority(menuCode));
        }
        String password = "{bcrypt}"+sysUser.getPassword();
        SecurityUser securityUser = new SecurityUser(sysUser.getId(), username, password, simpleGrantedAuthorityList);
        return securityUser;
    }
}
